/* 
 * File:   Z3D_Mesh.cpp
 * Author: ferranferri
 * 
 * Created on June 6, 2013, 4:23 PM
 */

//#include <GL/glext.h>
#include "Z3D_Mesh.h"
#include "../utils/glUtils.h"
#include "../internal/engine_constants.h"

namespace z3d{

    Z3D_Mesh::Z3D_Mesh(const std::string& name) 
        :_vertices(NULL)
        ,_nVertices(0)
        ,_name(name)
        ,_vertexArrayObjectId(0)
        ,_vertexBufferObjectId(0)
    {
    }

    void Z3D_Mesh::setVertices(const std::vector<float>& verts) {
        _nVertices = verts.size();
        _vertices = new float[_nVertices];
        std::copy(verts.begin(), verts.end(), _vertices);
    }
    void Z3D_Mesh::draw() {

        glClearColor(0, 0, 0, 1); // black
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // bind the program (the shaders)
        //glUseProgram(gProgram->object());

        // bind the VAO (the triangle)
        glBindVertexArray(_vertexArrayObjectId);

        // draw the VAO
        glDrawArrays(GL_TRIANGLES, 0, 3);

        // unbind the VAO
        glBindVertexArray(0);

        // unbind the program
        glUseProgram(0);

        // swap the display buffers (displays what was just drawn)
       // glfwSwapBuffers();
    }
     float Z3D_Mesh::vertexAt(uint32_t idx) {       
            return _vertices[idx];     
     }
     bool Z3D_Mesh::loadTriangles(/*const Program& p*/) {
        // make and bind the VAO
        glGenVertexArrays(1, &_vertexArrayObjectId);
        glBindVertexArray(_vertexArrayObjectId);

        // make and bind VBO
        glGenBuffers(1, &_vertexBufferObjectId);
        glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferObjectId);

        glBufferData(GL_ARRAY_BUFFER, sizeof(_vertices) * _nVertices, _vertices, GL_STATIC_DRAW);
        CHECK_OPENGL_ERROR;
        return true;
     }
     
     Z3D_Mesh::~Z3D_Mesh() {
        if(_vertices != 0)
                delete _vertices;
        _vertices = NULL;
    }

     GLuint Z3D_Mesh::getVertexBufferObjectId() const {
         return _vertexBufferObjectId;
     }

     GLuint Z3D_Mesh::getVertexArrayObjectId() const {
         return _vertexArrayObjectId;
     }

}